import { defineStore } from 'pinia';
import { useCanvasPersistence } from '@/hooks/usePersistence';

// 画布初始状态
const DEFAULT_CANVAS_STATE = {
  scale: 1, // 默认缩放比例 1:1
  offset: { x: 0, y: 0 }, // 默认偏移量（画布左上角对齐容器）
  containerSize: { width: 1200, height: 800 }, // 默认容器尺寸
};

export const useCanvasStore = defineStore('canvas', {
  state: () => ({
    ...DEFAULT_CANVAS_STATE, // 解构初始状态
  }),
  actions: {
    // 更新画布状态（批量修改）
    updateCanvasState(updates: Partial<typeof DEFAULT_CANVAS_STATE>) {
      Object.assign(this, updates);
    },
    // 重置画布状态（同时清除存储）
    async resetCanvasState() {
      Object.assign(this, DEFAULT_CANVAS_STATE);
      await import('@/utils/storageHelper').then(({ clearStorage, STORAGE_KEYS }) => {
        clearStorage(STORAGE_KEYS.CANVAS_STATE);
      });
    },
  },
  // 初始化时集成持久化
  setup() {
    // 调用持久化钩子，传入当前 Store 状态
    const { manualSaveCanvas } = useCanvasPersistence({
      get scale() { return useCanvasStore().scale; },
      get offset() { return useCanvasStore().offset; },
      get containerSize() { return useCanvasStore().containerSize; },
    });

    // 暴露手动保存方法到 Store
    return { manualSaveCanvas };
  },
});